Interfaces
In C#, you can fully separate a class’ interface from its implementation by using the keyword interface. Interfaces are syntactically similar to abstract classes. However, in an interface, no method can include a body.
Sysntax:
interface name
{
ret-type method-name1(param-list);
ret-type method-name2(param-list);
// ...
ret-type method-nameN(param-list);
}
Program on Interface
using System;
interface abc
{
void put(int x, int y);
}
class xyz : abc
{
public void put(int x, int y)
{
Console.WriteLine("Sum" + (x + y));
}
public void put1(int x, int y)
{
Console.WriteLine("Sub" + (x - y));
}
}
class Sample
{
public static void Main(String[] args)
{
xyz x = new xyz();
x.put(10, 5);
x.put1(5, 3);
abc k = new xyz();
k.put(2, 3);
// k.put1(2, 4); not accessable in reference
}
}
Program on inheritance of interfaces and classes.
using System;
interface abc
{
void sum(int x, int y);
}
interface abc1:abc
{
void sub(int x, int y);
}
interface xyz
{
void mul(int x, int y);
}
interface xyz1
{
void div(int x, int y);
}
class pqr : abc1
{
public void sum(int x, int y)
{
Console.WriteLine("Sum" + (x + y));
}
public void sub(int x, int y)
{
Console.WriteLine("Sub" + (x - y));
}
}
class mno : pqr, xyz, xyz1
{
public void mul(int x, int y)
{
Console.WriteLine("Mul" + (x * y));
}
public void div(int x, int y)
{
Console.WriteLine("Div" + (x / y));
}
}
class Sample
{
public static void Main(String[] args)
{
mno x = new mno();
x.sum(5, 3);
x.sub(5, 2);
x.mul(10, 2);
x.div(20, 2);
Console.WriteLine("Polymorphisam acess");
abc k;
k = x;
k.sum(23, 2); // only we can acess sum with K
abc1 p;
p = x;
p.sub(4, 1);
p.sum(12, 2); //we can acees only sum and sub methods
}
}
Partial keyword
Partial types allow you to divide the definition of a single type into multiple parts. Although the parts can be in the same file, they are typically used to divide an object definition among multiple files.
using System;
partial interface abc
{
void sum(int x, int y);
}
partial interface abc
{
void sub(int x, int y);
}
class mno :abc
{
public void sum(int x, int y)
{
Console.WriteLine("sum" + (x + y));
}
public void sub(int x, int y)
{
Console.WriteLine("sub" + (x - y));
}
}
class Sample
{
public static void Main(String[] args)
{
mno x = new mno();
x.sum(10, 2);
x.sub(5, 3);
}
}